/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.dianlan.bits;

import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.component.gateway.core.util.HexUtil;
import info.peigen.hotpot.component.gateway.dianlan.bits.base.BitParserBase;
import info.peigen.hotpot.component.gateway.dianlan.facade.enums.DianlanHeatingContactorStatus;
import info.peigen.hotpot.component.gateway.dianlan.protocol.passive.DianlanBatteryStatusInfo;

/**
 * <b>(DianlanBatteryStatusInfoReasonBits)</b>
 * <p>
 * 单体电池状态解析
 *
 * @author LiDaHai
 * @version 1.0.0
 * @since 2023/1/12
 */
public class DianlanBatteryStatusInfoReasonBits extends BitParserBase {

    public DianlanBatteryStatusInfo parseReason(String hexString) {
        String[]                 hexStrArray       = hexStrToArray(hexString);
        DianlanBatteryStatusInfo batteryStatusInfo = DianlanBatteryStatusInfo.builder().build();
        batteryStatusInfo.setHighestVoltage(1.25d * parseInt(StrUtil.sub(hexStrArray[1], 1, 2) + hexStrArray[0]));
        batteryStatusInfo.setLowestVoltage(1.25d * parseInt(hexStrArray[2] + StrUtil.sub(hexStrArray[1], 0, 1)));
        batteryStatusInfo.setAverageVoltage(1.25d * parseInt(StrUtil.sub(hexStrArray[4], 1, 2) + hexStrArray[3]));
        String bitString = HexUtil.hexToBinary(hexStrArray[4]);
        batteryStatusInfo.setReserve(StrUtil.sub(bitString, 4, 6));
        batteryStatusInfo.setHeatingContactorStatus(parseHeatingContactorStatus(StrUtil.sub(bitString, 6, 8)));
        batteryStatusInfo.setHighestVoltageNumber(parseInt(StrUtil.sub(hexStrArray[6], 1, 2) + hexStrArray[5]));
        batteryStatusInfo.setLowestVoltageNumber(parseInt(hexStrArray[7] + StrUtil.sub(hexStrArray[6], 0, 1)));
        return batteryStatusInfo;
    }

    private DianlanHeatingContactorStatus parseHeatingContactorStatus(String bitString) {
        switch (bitString) {
            case "00":
                return DianlanHeatingContactorStatus.Invalid;
            case "01":
                return DianlanHeatingContactorStatus.BreakOff;
            case "10":
                return DianlanHeatingContactorStatus.Close;
            case "11":
                return DianlanHeatingContactorStatus.Fault;
            default:
                return DianlanHeatingContactorStatus.UNKNOWN;
        }
    }
}